﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Colorful.Cache
{
    #region RedisCache
    /// <summary>
    /// Redis缓存
    /// </summary>
    public class RedisCacheService : ICacheService, IDisposable
    {
        private RedisCache _redis;

        #region 初始化
        /// <summary>
        /// 初始化RedisCacheHelper
        /// </summary>
        /// <param name="prefix">用于存储Key的前辍（必填）</param>
        public RedisCacheService(string prefix)
            : this(prefix, "localhost:6379")
        {
        }
        /// <summary>
        /// 初始化RedisCacheHelper
        /// </summary>
        /// <param name="prefix">缓存前辍如：colorful</param>
        /// <param name="connectionString">连接字符串，如：localhost:6379,password=xxx</param>
        public RedisCacheService(string prefix, string connectionString)
        {
            _redis = new RedisCache(prefix, connectionString);
        }
        #endregion

        public bool Exists(string key)
        {
            return _redis.Exists(key);
        }

        public void Set<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?))
        {
            _redis.Set(key, value, expiry);
        }

        public Task<bool> SetAsync<T>(string key, T value, TimeSpan? expiry = default(TimeSpan?))
        {
            return _redis.SetAsync(key, value, expiry);
        }

        public async void Remove(string key)
        {
            await _redis.RemoveAsync(key);
        }

        public Task<bool> RemoveAsync(string key)
        {
            return _redis.RemoveAsync(key);
        }

        public T Get<T>(string key, Func<T> requireData = null, TimeSpan? expiry = default(TimeSpan?))
        {
            return _redis.Get(key, requireData, expiry);
        }

        public Task<T> GetAsync<T>(string key, Func<T> requireData = null, TimeSpan? expiry = default(TimeSpan?))
        {
            return _redis.GetAsync(key, requireData, expiry);
        }

        #region Dispose
        public void Dispose()
        {
            _redis.Dispose();
        }
        #endregion
    }
    #endregion
}
